package leetcode.D100.T39;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    // 一刷
    /*public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        Arrays.sort(candidates);
        dfs(result, path, candidates, target, 0);
        return result;
    }
    private void dfs(List<List<Integer>> result, List<Integer> path, int[] candidates, int target, int last) {
        if(target == 0) {
            result.add(new ArrayList<>(path));
            return;
        }
        for(int i=last; i<candidates.length; ++i) {
            if(target - candidates[i] < 0) {
                break;
            }
            path.add(candidates[i]);
            dfs(result, path, candidates, target-candidates[i], i);
            path.remove(path.size()-1);
        }
    }*/

    // 二刷
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
        dfs(result, temp, candidates, target, 0, 0);
        return result;
    }

    private void dfs(List<List<Integer>> result, List<Integer> temp,
                     int[] candidates, int target, int sum, int cur) {
        if (cur == candidates.length)
            return;
        if (sum == target) {
            result.add(new ArrayList<>(temp));
            return;
        } else if (sum > target)
            return;
        temp.add(candidates[cur]);
        dfs(result, temp, candidates, target, sum + candidates[cur], cur);
        temp.remove(temp.size()-1);
        dfs(result, temp, candidates, target, sum, cur+1);
    }
}